//
//  TabMineActivityTableViewController.swift
//  kz
//
//  Created by Tech_001 on 17/8/2017.
//  Copyright © 2017 Tech_001. All rights reserved.
//

import Foundation
import UIKit
import MJRefresh

 
class TabMineActivityTableViewController: UITableViewController{
    var activityDataChange:[[String:Any]]?
    var activityData: [[String:Any]]=[]
    var activityCoverImageView: [String:UIImageView] = [:]
    var activityfeatureImageFor: [String:UIImage] = [:]
    var activityfeatureImageHeightFor: [String:CGFloat] = [:]
    var mtNavigation:UINavigationController?
    var mtCode:String?
    
    
    let rc: MJRefreshHeader? = MJRefreshNormalHeader()
    func classification(){
        if let activitycategoryData = GlobalInfo.activitycategoryData {
       
        self.activityData=[]
        if(mtCode == "0"){
            self.activityData = self.activityDataChange!
        }else{
            for activityItem in self.activityDataChange! {
                if let actypeid=activityItem["actypeid"] as? String{
                        if(Int(mtCode!)!<activitycategoryData.count){
                    if(actypeid==activitycategoryData[(Int(mtCode!)!)]["atype"] as! String){
                        self.activityData.append(activityItem)
                    }
                    }
                }
            }
        }
        }
        
        
//        else if(mtCode == "2"){
//            for activityItem in self.activityDataChange! {
//                if let actypeid=activityItem["actypeid"] as? String{
//                    if(actypeid=="1008"){
//                        self.activityData.append(activityItem)
//                    }
//                }
//            }
//        }else if(mtCode == "3"){
//            for activityItem in self.activityDataChange! {
//                if let actypeid=activityItem["actypeid"] as? String{
//                    if(actypeid=="1009"){
//                        self.activityData.append(activityItem)
//                    }
//                }
//            }
//        }else if(mtCode == "4"){
//            for activityItem in self.activityDataChange! {
//                if let actypeid=activityItem["actypeid"] as? String{
//                    if(actypeid=="1010"){
//                        self.activityData.append(activityItem)
//                    }
//                }
//            }
//        }else if(mtCode == "5"){
//            for activityItem in self.activityDataChange! {
//                if let actypeid=activityItem["actypeid"] as? String{
//                    if(actypeid=="1011"){
//                        self.activityData.append(activityItem)
//                    }
//                }
//            }
//        }else if(mtCode == "6"){
//            for activityItem in self.activityDataChange! {
//                if let actypeid=activityItem["actypeid"] as? String{
//                    if(actypeid=="1012"){
//                        self.activityData.append(activityItem)
//                    }
//                }
//            }
//        }else if(mtCode == "7"){
//            for activityItem in self.activityDataChange! {
//                if let actypeid=activityItem["actypeid"] as? String{
//                    if(actypeid=="1013"){
//                        self.activityData.append(activityItem)
//                    }
//                }
//            }
//        }
    }
    
    override func viewDidAppear(_ animated: Bool) {
        if(GlobalInfo.listActivityBack){
            pullToRefresh();
            GlobalInfo.listActivityBack=false
        }
    }
    override func viewDidLoad() {
        classification();
//        let image = UIImage(named: "top2_icon")
//        self.navigationItem.titleView = UIImageView(image: image)
////        let topLogo = UIImage(named: "top_icon")
////        let ratio = topLogo!.size.height/topLogo!.size.width
////        let newWidth = UIHelper.fullSize.width * 0.4
////        let newHeight = newWidth * ratio
////
////        let titleView = UIView()
////        let topLogoView = UIImageView(image: topLogo)
////
////        titleView.addSubview(topLogoView)
//        topLogoView.contentMode = .scaleToFill
//        topLogoView.frame = CGRect(x: -(newWidth/2), y: -(newHeight/2), width: newWidth, height: newHeight)
//
//        self.navigationItem.titleView = titleView
        self.navigationController?.setNavigationBarHidden(true, animated: false)
        self.tableView.estimatedRowHeight = 200.0
        //self.tableView.rowHeight = UITableViewAutomaticDimension
        
        rc!.setRefreshingTarget(self, refreshingAction: #selector(self.pullToRefresh))
        self.tableView.mj_header = rc
        self.tableView.setNeedsLayout()
        self.tableView.layoutIfNeeded()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        navigationController?.setNavigationBarHidden(false, animated: true)
       // pullToRefresh()
    }
    
    override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return UITableView.automaticDimension
    }
    
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.activityData.count
    }
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "customCell", for: indexPath) as! TabMineActivityTableViewCell
        
        let activity = self.activityData[indexPath.row]
        cell.titleLabel.text = activity["actname"] as? String
        cell.contentLabel.text = activity["actdesc"] as? String
        cell.joinButton.isUserInteractionEnabled = false
        
        if cell.contentLabel.text?.count == 0 {
            cell.contentLabel.text = " "
        }
        
        cell.joinButton.setTitleColor(UIColor.darkGray, for: .normal)
        
        if UserHelper.getLoginStatus() {
            if let show = activity["show"] as? String {
                if show.count > 0 {
                    cell.joinButton.setTitle(show, for: .normal)
                    
                    if let canJoin = activity["canJoin"] as? Bool {
                        if canJoin == true{
                            cell.joinButton.setTitleColor(UIColor.init(red: 0.08, green: 0.49, blue: 0.98, alpha: 1), for: .normal)
                        }
                    }

                }else{
                    cell.joinButton.setTitle("登陆参与", for: .normal)
                }
            }
        }else{
            cell.joinButton.setTitle("登陆参与", for: .normal)
        }
        
        activityCoverImageView[activity["actid"] as! String] = cell.featureImageView
        
        if let image = self.activityfeatureImageFor[activity["actid"] as! String] {
            cell.featureImageView.image = image
            cell.imageHeightConstraint.constant = self.activityfeatureImageHeightFor[activity["actid"] as! String]!
        }else{
            cell.featureImageView.image = UIImage(named: "img_default_banner")
            if let url = activity["cover"] as? String {
                if let urlObject = URL(string: url) {
                    RequestHelper.get(atPath: "/iimg/\(urlObject.path)", withCompletion: { data in
                        DispatchQueue.main.async {
                            let image = UIImage(data: data)
                            
                            let width = image!.size.width
                            let height = image!.size.height
                            let bounds = cell.featureImageView.bounds
                            let adjustedHeight = height * (bounds.width/width)
                            
                            cell.featureImageView.image = image
                            self.activityfeatureImageFor[activity["actid"] as! String] = image
                            self.activityfeatureImageHeightFor[activity["actid"] as! String] = adjustedHeight
                            
                            cell.imageHeightConstraint.constant = adjustedHeight
                            cell.setNeedsDisplay()
                            cell.layoutIfNeeded()
                            //tableView.reloadRows(at: [indexPath], with: .none)
                        }
                    }, withError: { error in
                       
                        DispatchQueue.main.async{
                             UIHelper.alertSimpleMessage(about: "服务器异常.\(getErrorString())", withDescription: "", in: self)
                            cell.featureImageView.image = UIImage(named: "img_default_60")
                        }
                    })
                }
            }
        }
        
        /**** StackView ****/
        let stackView = TZStackView()
        stackView.axis = .vertical
        
        cell.contentView.addSubview(stackView)
        
        stackView.translatesAutoresizingMaskIntoConstraints = false
        stackView.anchors.topAnchor.constraintEqualToAnchor(anchor: cell.contentView.anchors.topAnchor, constant: 4).isActive = true
        stackView.anchors.bottomAnchor.constraintEqualToAnchor(anchor: cell.contentView.anchors.bottomAnchor).isActive = true
        stackView.anchors.leadingAnchor.constraintEqualToAnchor(anchor: cell.contentView.anchors.leadingAnchor).isActive = true
        stackView.anchors.trailingAnchor.constraintEqualToAnchor(anchor: cell.contentView.anchors.trailingAnchor).isActive = true
        
        stackView.addArrangedSubview(cell.featureImageView)
        stackView.addArrangedSubview(cell.textContentView)
        
        return cell
    }
    
    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let activity = self.activityData[indexPath.row]
        let goNext =  TabMineActivityDetailViewController.instanceFromStoryboard()!
        goNext.activity = activity
        let actid = self.activityData[indexPath.row]["actid"]
        goNext.activityImage = self.activityfeatureImageFor[actid as! String]
        goNext.activityImageHeight = self.activityfeatureImageHeightFor[actid as! String]
        goNext.hidesBottomBarWhenPushed = true
        //self.navigationController?.pushViewController(goNext,animated: true)
    //   mtNavigation?.popToRootViewController(animated: true)
        //实现闭包,获取到传递的参数
        goNext.listIndex = indexPath.row
        goNext.callBackBlock { (updateTitle,index) in
            var activity = self.activityData[indexPath.row]
            activity["canJoin"] = "5"
            activity["actname"] = updateTitle
            self.activityData[indexPath.row] = activity
            self.tableView.reloadData()
        }
     mtNavigation?.pushViewController(goNext, animated: true)
        
       //  goNext.hidesBottomBarWhenPushed = false
   
        tableView.deselectRow(at: indexPath, animated: true)
    }

    @objc func pullToRefresh(){
        self.activityCoverImageView.removeAll()
        //获取测试环境的接口 2018.6.4 以前注释的是最早的接口
       // RequestHelper.get(atPath: "/clientsAPIs/activity", withCompletion: { data in
        RequestHelper.get(atPath: "/clientsAPIs/myactivity", withCompletion: { data in
            let activityInfoArray = try JSONSerialization.jsonObject(with: data, options: []) as! [[String: Any]]
            self.activityDataChange = activityInfoArray
        
            self.classification()
            DispatchQueue.main.async {
                self.tableView.reloadData()
                self.rc?.endRefreshing()
            }
            
        }, withError: { error in
            DispatchQueue.main.async {
                self.rc?.endRefreshing()
                UIHelper.alertSimpleMessage(about: "刷新失败", withDescription: "未成功刷新活动列表，请稍后重试\(getErrorString())", in: self)
            }
        })
    }
}
